package service

import (
	"context"

	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// UserService 用户服务
type UserService struct {
	pb.UnimplementedUserServer

	uc  *biz.UserUsecase
	log *log.Helper
}

// NewUserService 创建用户服务实例
func NewUserService(uc *biz.UserUsecase, logger log.Logger) *UserService {
	return &UserService{
		uc:  uc,
		log: log.NewHelper(logger),
	}
}

// Register 用户注册
func (s *UserService) Register(ctx context.Context, req *pb.RegisterRequest) (*pb.RegisterReply, error) {
	user, err := s.uc.Register(ctx, req.Username, req.Password, req.Email, req.Phone, req.Nickname)
	if err != nil {
		s.log.Errorf("用户注册失败: %v", err)
		return nil, err
	}

	return &pb.RegisterReply{
		UserId:  user.ID,
		Message: "注册成功",
	}, nil
}

// Login 用户登录
func (s *UserService) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginReply, error) {
	user, err := s.uc.Login(ctx, req.Username, req.Password)
	if err != nil {
		s.log.Errorf("用户登录失败: %v", err)
		return nil, err
	}

	// TODO: 生成JWT token
	token := "mock_token_" + req.Username

	return &pb.LoginReply{
		UserId:  user.ID,
		Token:   token,
		Message: "登录成功",
	}, nil
}

// GetUserInfo 获取用户信息
func (s *UserService) GetUserInfo(ctx context.Context, req *pb.GetUserInfoRequest) (*pb.GetUserInfoReply, error) {
	user, err := s.uc.GetUserInfo(ctx, req.UserId)
	if err != nil {
		s.log.Errorf("获取用户信息失败: %v", err)
		return nil, err
	}

	if user == nil {
		return nil, biz.ErrUserNotExists
	}

	return &pb.GetUserInfoReply{
		UserInfo: &pb.UserInfo{
			UserId:    user.ID,
			Username:  user.Username,
			Nickname:  user.Nickname,
			Email:     user.Email,
			Phone:     user.Phone,
			Avatar:    user.Avatar,
			Points:    user.Points,
			CreatedAt: timestamppb.New(user.CreatedAt),
			UpdatedAt: timestamppb.New(user.UpdatedAt),
		},
	}, nil
}

// UpdateUserInfo 更新用户信息
func (s *UserService) UpdateUserInfo(ctx context.Context, req *pb.UpdateUserInfoRequest) (*pb.UpdateUserInfoReply, error) {
	err := s.uc.UpdateUserInfo(ctx, req.UserId, req.Nickname, req.Email, req.Phone, req.Avatar)
	if err != nil {
		s.log.Errorf("更新用户信息失败: %v", err)
		return nil, err
	}

	return &pb.UpdateUserInfoReply{
		Message: "更新成功",
	}, nil
}

// GetUserPoints 获取用户积分
func (s *UserService) GetUserPoints(ctx context.Context, req *pb.GetUserPointsRequest) (*pb.GetUserPointsReply, error) {
	points, err := s.uc.GetUserPoints(ctx, req.UserId)
	if err != nil {
		s.log.Errorf("获取用户积分失败: %v", err)
		return nil, err
	}

	return &pb.GetUserPointsReply{
		Points:  points,
		Message: "获取成功",
	}, nil
}

// GetPointsHistory 获取积分历史记录
func (s *UserService) GetPointsHistory(ctx context.Context, req *pb.GetPointsHistoryRequest) (*pb.GetPointsHistoryReply, error) {
	// 这里需要调用积分服务，暂时返回空数据
	// TODO: 集成积分服务
	return &pb.GetPointsHistoryReply{
		Records: []*pb.PointsRecord{},
		Total:   0,
		Message: "获取成功",
	}, nil
}
